package com.luxuewen.sxa.service.impl;

import com.luxuewen.sxa.common.exception.ApiException;
import com.luxuewen.sxa.service.CommonService;
import com.luxuewen.sxa.utils.UPYUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author wen
 */
@Service
public class CommonServiceImpl implements CommonService {
    public String upload (MultipartFile file) {
        String url;
        try {
            url = UPYUtils.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(40101, e.getMessage());
        }
        return url;
    }

    /**
     * 生成树状结构
     * @param data 总数据集
     * @param base 一级数据集
     * @return 树结构
     */
    public List<Map<String, Object>> tree (List<Map<String, Object>> data, List<Map<String, Object>> base) {
        for (Map<String, Object> parent : base) {
            List<Map<String, Object>> children = new ArrayList<>();
            for (Map<String, Object> child : data) {
                if (Objects.equals(parent.get("id").toString(), child.get("parent_id").toString())) {
                    children.add(child);
                }
            }
            // 递归子节点
            children = this.tree(data, children);
            parent.put("children", children);
        }

        return base;
    }

}


